We now need to look through the messages and then find one with a particular number which we then print. I can use the fact that to find message n I must look for n '*
' characters. For this to work I have to use the computer convention of starting counting at 0. To get the first (i.e. zeroth) message I must therefore look for 0 '*
' characters, which places me at the start of the array.
As a further example example, I will get the fifth message (number 4) by looking for 4 '*
' characters. Once I have found the start of the messages I then print out characters in the message until I find the * which marks the end of that message.
I have decided to implement this as a function called show_message
. I will tell show_message
the number of the message I want and it will then find that message and print it.
On the right I have put my first version of show_message
. The idea is that it moves down the messages array. Each time it finds a '*
' character it subtracts 1 from the number of the message it is supposed to be finding. When this number reaches 0 it moves to the second while loop and prints out characters until it finds the '*
' character at the end of the message. In each case I have decided to use a while loop construction and I wrote the code you see.
It doesn't work. When you call the function it never comes back, indicating that something is wrong. I am fairly sure that my approach is valid, but I must have got something wrong when I wrote the code. Welcome to the world of debugging.
void show_message(
unsigned char number)
{
int pos = 0 ;
/* find the start of message */
while ( number > 0 )
{
if ( messages [pos] == '*' )
{
number = number - 1 ;
}
}
/* print the message */
while ( messages[pos]!='*' )
{
lcd_print_ch (messages[pos]) ;
pos = pos + 1 ;
}
}